package com.zzy.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzy.model.User;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * 在索引下 修改
 *
 */
public class UpdateModel {

    public static void main(String[] args) {
        test();
    }

    public static void test() {
        HttpHost httpHost = new HttpHost("192.168.15.128", 9200, "http");
        RestClientBuilder rb = RestClient.builder(httpHost);

        rb.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                return builder.setConnectTimeout(20000)// 链接超时  毫秒
                        .setSocketTimeout(20000) // 请求超时  毫秒
                        ;
            }
        });

        RestHighLevelClient client = new RestHighLevelClient(rb);

        try {
            System.out.println("打开了 elasticsearch 链接。");



            UpdateRequest request =   new UpdateRequest();
            request.index("zzyuser").id("1004");

            User user = new User();
            user.setName("王五4");
            user.setAge(30);
            user.setSex("男");


            ObjectMapper mapper = new ObjectMapper();
            String sData = mapper.writeValueAsString(user);

           request.doc(  sData, XContentType.JSON );

            //request.doc(   XContentType.JSON ,"sex","女");

            UpdateResponse response = client.update( request, RequestOptions.DEFAULT);

            System.out.println(response.getResult());



            client.close();//关闭链接
            System.out.println("关闭了 elasticsearch 链接。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
